#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 13:41:50 2019

@author: gloria

GRAPH A3

"""

# NB:: Adjust education and party 


# PACKAGES #############################################################

import pandas as pd
import os 
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib import rcParams

# COMPUTER #############################################################

computer = 'glgennaro'  # work
# computer = 'gloria' #personal


# SETTINGS          #####################################################
# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27


# CONGRESS 2020 #####################################################

os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/dta')
df = pd.read_stata('congress_election_complete2020.dta')

# gender 
df_f = df[df.gender!='']
df_f = df_f.groupby(['gender']).mean().reset_index()
df_f = df_f[['gender','pop_dim2']]
df_f.columns = ['gender', 'mean']
df_s = df.groupby(['gender']).std().reset_index()
df_s = df_s[['gender','pop_dim2']]
df_s.columns = ['gender', 'std']
df_t = pd.merge(df_f, df_s, on='gender')

df_t['label'] = ['Female', 'Male']

x = np.array(df_t.index)
y = np.array(df_t['mean'])
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0,  size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15);

os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_gender2020.png')



# incumbent 

df_f = df.groupby(['incumbent']).mean().reset_index()
df_f = df_f[['incumbent','pop_dim2']]
df_f.columns = ['incumbent', 'mean']
df_s = df.groupby(['incumbent']).std().reset_index()
df_s = df_s[['incumbent','pop_dim2']]
df_s.columns = ['incumbent', 'std']
df_t = pd.merge(df_f, df_s, on='incumbent')

df_t['label'] = ['Non Incumbent', 'Incumbent']

x = np.array(df_t.index)
y = np.array(df_t['mean']) 
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0,  size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15);


os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_incumbent2020.png')


# outsider

plt.clf()

df_f = df.groupby(['outsider2']).mean().reset_index()
df_f = df_f[['outsider2','pop_dim2']]
df_f.columns = ['outsider', 'mean']
df_s = df.groupby(['outsider']).std().reset_index()
df_s = df_s[['outsider','pop_dim2']]
df_s.columns = ['outsider', 'std']
df_t = pd.merge(df_f, df_s, on='outsider')

df_t['label'] = ['Insider', 'Outsider']

x = np.array(df_t.index)
y = np.array(df_t['mean']) 
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0,  size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15);


os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_outsider2020.png')



# party: need to define unique valies of party

plt.clf()

df['party_short'] = np.where(
	df['party'] == 'D', 'D', np.where(
		df['party'] == 'R', 'R', np.where(
			df['party'] == 'R ', 'R', 'Other')))

# df['party_short'] = df['party']
# for i in range(len(df['party_short'])):
# 	if df['party_short'][i].startswith('D'):
#         df['party_short'][i] = 'D'
#     elif df['party_short'][i].startswith('R'):
#         df['party_short'][i] = 'R'
#     else:
#         df['party_short'][i] = 'Others'

df_f = df.groupby(['party_short']).mean().reset_index()
df_f = df_f[['party_short', 'pop_dim2']]
df_f.columns = ['party_short', 'mean']
df_s = df.groupby(['party_short']).std().reset_index()
df_s = df_s[['party_short', 'pop_dim2']]
df_s.columns = ['party_short', 'std']
df_t = pd.merge(df_f, df_s, on='party_short')

df_t['label'] = ['Democrats', 'Others', 'Republicans']

x = np.array(df_t.index)
y = np.array(df_t['mean'])
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0, size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15)

os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_democrat2020.png')


# competitive
plt.clf()
df_f = df.groupby(['competitive20']).mean().reset_index()
df_f = df_f[['competitive20', 'pop_dim2']]
df_f.columns = ['competitive20', 'mean']
df_s = df.groupby(['competitive20']).std().reset_index()
df_s = df_s[['competitive20', 'pop_dim2']]
df_s.columns = ['competitive20', 'std']
df_t = pd.merge(df_f, df_s, on='competitive20')

df_t['label'] = ['Non Competitive', 'Competitive']

x = np.array(df_t.index)
y = np.array(df_t['mean'])
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0, size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15)

os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_comp2020.png')



# education

df4 = df[['education', 'pop_dim2']]
df4['educ'] = df4['education']

for i in range(len(df4['educ'])):
    if df4['educ'][i]=='MBA':
        df4['educ'][i]='college degree'
    elif df4['educ'][i]=='PHD':
        df4['educ'][i]='college degree'
    elif df4['educ'][i]=='Law':
        df4['educ'][i]='college degree'
    else:
        continue


df_f = df4.groupby(['educ']).mean().reset_index()
df_f = df_f[['educ','pop_dim2']]
df_f.columns = ['educ', 'mean']
df_s = df4.groupby(['educ']).std().reset_index()
df_s = df_s[['educ','pop_dim2']]
df_s.columns = ['educ', 'std']
df_t = pd.merge(df_f, df_s, on='educ')
df_t = df_t[1:]

df_t['label'] = ['Tertiary +', 'Secondary']

x = np.array(df_t.index)
y = np.array(df_t['mean'])
e = np.array(df_t['std'])
x_pos = np.arange(len(df_t.index))

fig, ax = plt.subplots()
ax.bar(x_pos, y, yerr=e, align='center', alpha=0.5, ecolor='black', capsize=10)
ax.set_ylabel('Populism', size=30)
ax.set_xticks(x_pos)
ax.set_xticklabels(df_t['label'], rotation=0, size=30)
ax.yaxis.grid(True)
ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
ax.tick_params(axis='y', which='major', labelsize=15)


os.chdir('/Users/' + computer + '/Dropbox/Progetti/Rhetoric/Replication Packages/RP_2020_v2/Graphs')
plt.savefig('cong_educ2020.png')